
const VodafoneGhsPageTag = require("./vodafoneGhsPageTag.js");
const Constant = require("./constant.js");
const ApiUrl = require("./baseApiUrl.js");
const BaseStringUtil = require("./baseStringUtil.js");
const RunDefine = require("./baseRunDefine.js");
const BaseKeyboardDefine = require("./baseKeyboardDefine.js");
const BaseHttpUtil = require("./baseHttpUtil.js");

/** pin 首个输入框坐标 */
const pinEditPoint = {
    x: 150,
    y: 860
}

/** 根据数字获取数字键盘坐标 */
const getNumberKeoyboardPoint = (num) => {
    if ("0" === num) {
        return BaseKeyboardDefine.code0;
    } else if ("1" === num) {
        return BaseKeyboardDefine.code1;

    } else if ("2" === num) {
        return BaseKeyboardDefine.code2;

    } else if ("3" === num) {
        return BaseKeyboardDefine.code3;

    } else if ("4" === num) {
        return BaseKeyboardDefine.code4;

    } else if ("5" === num) {
        return BaseKeyboardDefine.code5;

    } else if ("6" === num) {
        return BaseKeyboardDefine.code6;

    } else if ("7" === num) {
        return BaseKeyboardDefine.code7;

    } else if ("8" === num) {
        return BaseKeyboardDefine.code8;

    } else if ("9" === num) {
        return BaseKeyboardDefine.code9;

    }
    return null;
}

/** 判断输入pin是否成功 */
const doIsInputPinCodeSuccess = () => {
    // 先缩起键盘
    click(BaseKeyboardDefine.codeClose.x, BaseKeyboardDefine.codeClose.y);
    sleep(1000);

    console.log(Constant.UI_SDK_VERSION + "doPin-点击第1个框: " + pinEditPoint.x + ", " + pinEditPoint.y);

    // 先点击一下输入框
    click(pinEditPoint.x, pinEditPoint.y);
    sleep(1000);

    let allInput = true;
    let pinCodes = Constant.getPin();
    if (pinCodes.length >= 4) {
        sleep(500);
        let code1 = pinCodes.substring(0, 1);
        let code1Point = getNumberKeoyboardPoint(code1);
        if (code1Point) {
            click(code1Point.x, code1Point.y);
            sleep(500);
        } else {
            allInput = false;
        }

        let code2 = pinCodes.substring(1, 2);
        let code2Point = getNumberKeoyboardPoint(code2);
        if (code2Point) {
            click(code2Point.x, code2Point.y);
            sleep(500);
        } else {
            allInput = false;
        }

        let code3 = pinCodes.substring(2, 3);
        let code3Point = getNumberKeoyboardPoint(code3);
        if (code3Point) {
            click(code3Point.x, code3Point.y);
            sleep(500);
        } else {
            allInput = false;
        }

        let code4 = pinCodes.substring(3, 4);
        let code4Point = getNumberKeoyboardPoint(code4);
        if (code4Point) {
            click(code4Point.x, code4Point.y);
            sleep(1000);
        } else {
            allInput = false;
        }

        return allInput;
    }
    return false;
}

/** pin输入，点击键盘 */
const doInputPinCode = () => {
    // 循环判断是否为 pin输入成功
    for (let rIndex = 0; rIndex < RunDefine.loopQueryCount; rIndex++) {
        if (doIsInputPinCodeSuccess()) {
            sleep(1000);
            return true;
        }

        sleep(1 * 1000);
    }
    return false;
}


// 操作 登录
const doLogin = () => {
    let editList = className("EditText").find();
    // console.log("doLogin-判断是否为登录页-editList " +editList.length)
    console.log(Constant.UI_SDK_VERSION + "doLogin-开始操作登录");
    for (let index = 0; index < editList.length; index++) {
        let tv = editList[index];
        let curText = tv.text() || ""
        console.log(Constant.UI_SDK_VERSION + "doLogin-当前: " + index + ", 内容: " + curText)

        if (curText.indexOf(VodafoneGhsPageTag.loginPageTag1) !== -1) {
            console.log(Constant.UI_SDK_VERSION + "doLogin-设置登录手机号: " + Constant.getMtn());
            tv.setText(Constant.getMtn());

            sleep(500);
            back();
            sleep(1000);
            console.log(Constant.UI_SDK_VERSION + "doLogin-点击登录");
            click(device.width * 0.5, device.height - 60); // 提交按钮
            sleep(500);

            editList.length = 0;
            editList = null;
            return true;
        }
    }

    editList.length = 0;
    editList = null;
    console.log(Constant.UI_SDK_VERSION + "doLogin-操作登录结束: 当前不是登录页")
    return false;
}

// 操作 登录-pin
const doPin = () => {
    console.log(Constant.UI_SDK_VERSION + "doPin-开始操作登录-pin");
    return doInputPinCode();
}

// 操作 打开 home 页
const doClickHomeTab = () => {
    // 点击 Cash
    console.log(Constant.UI_SDK_VERSION + "doClickHomeTab-开始操作打开 Home 页");
    click(device.width / 10 * 3, device.height - 60);
    sleep(1000);
    return true;
}

/** 获取余额 */
const doGetHomeBalance = () => {
    let textList = className("TextView").find();
    for (let index = 0; index < textList.length; index++) {
        let tv = textList[index];
        let curText = tv.text() || ""
        // console.log(Constant.UI_SDK_VERSION + "doGetHomeBalance-当前: " + index + ", 内容: " + curText)

        if (curText.indexOf("GHS") !== -1) {
            console.log(Constant.UI_SDK_VERSION + "doGetHomeBalance-拿到余额: " + curText);
            textList.length = 0;
            textList = null;
            return curText;
        }
    }
    textList.length = 0;
    textList = null;
    return "";
}

// 操作 打开 send money 页
const doClickSendMoney = () => {
    // 点击 Send money
    console.log(Constant.UI_SDK_VERSION + "doOpenSendMoneyPage-开始操作打开 Send money 页");
    sleep(500);
    click(VodafoneGhsPageTag.homePageTag3);
    sleep(1000);
    return true;
}

// 操作 打开 send money 页
const doClickVodafonePayment = () => {
    // 点击 Send money
    console.log(Constant.UI_SDK_VERSION + "doClickVodafonePayment-开始操作打开 Vodafone Payment 页");
    sleep(500);
    click(VodafoneGhsPageTag.sendMoneyPageTag2);
    sleep(1000);
    return true;
}

// 操作 输入对方钱包号
const doInputTargetAccount = (targetMtn, targetAmount, targetReference) => {
    // 输入对方钱包号
    console.log(Constant.UI_SDK_VERSION + "doInputTargetAccountPage-开始操作输入对方钱包号");
    console.log(Constant.UI_SDK_VERSION + "doInputTargetAccountPage-" + targetMtn + ", " + targetAmount + ", " + targetReference);

    let editList = className("EditText").find();
    let findTag1 = false;
    let findTag2 = false;
    let findTag3 = false;

    if (editList.length >= 3) {
        let edit1 = editList[0];
        edit1.setText(targetMtn);

        let edit2 = editList[1];
        edit2.setText(targetAmount);

        let edit3 = editList[2];
        edit3.setText(targetReference);

        findTag1 = true;
        findTag2 = true;
        findTag3 = true;
    }

    // for (let index = 0; index < editList.length; index++) {
    //     let tv = editList[index];
    //     let curText = tv.text() || ""
    //     console.log(Constant.UI_SDK_VERSION + "doLogin-当前: " + index + " +内容: " + curText)

    //     if (curText.indexOf(VodafoneGhsPageTag.sendMoneyAccountInputPageTag1) !== -1) {
    //         console.log(Constant.UI_SDK_VERSION + "doInputTargetAccountPage-设置 input account: " + targetMtn);
    //         tv.setText(targetMtn);
    //         findTag1 = true;
    //     }
    //     if (curText.indexOf(VodafoneGhsPageTag.sendMoneyAccountInputPageTag2) !== -1) {
    //         console.log(Constant.UI_SDK_VERSION + "doInputTargetAccountPage-设置 input amount: " + targetAmount);
    //         tv.setText(targetAmount);
    //         findTag2 = true;
    //     }
    //     if (curText.indexOf(VodafoneGhsPageTag.sendMoneyAccountInputPageTag3) !== -1) {
    //         console.log(Constant.UI_SDK_VERSION + "doInputTargetAccountPage-设置 input reference: " + targetReference);
    //         tv.setText(targetAmount);
    //         findTag3 = true;
    //     }
    // }

    editList.length = 0;
    editList = null;

    if (findTag1 && findTag2 && findTag3) {
        sleep(500);
        click(VodafoneGhsPageTag.sendMoneyAccountInputPageTagSend);
        sleep(500);
    } else {
        console.log(Constant.UI_SDK_VERSION + "doInputTargetAccountPage-设置 输入错误");
        return false;
    }

    return true;
}

// 操作 点击确认转账
const doConfirmSendMoney = () => {
    // 输入对方钱包号
    console.log(Constant.UI_SDK_VERSION + "doConfirmSendMoneyPage-开始操作确认转账");

    // click(device.width * 0.5, device.height - 60); // 提交按钮
    click(VodafoneGhsPageTag.sendMoneyConfirmPageTagDone)
    sleep(500);
    return true;
}

// 操作 点击输入转账密码
const doInputSendMoneyPassword = () => {
    // 输入对方钱包号
    console.log(Constant.UI_SDK_VERSION + "doInputSendMoneyPassword-开始操作输入转账密码");
    return doInputPinCode();
}

// 操作 点击 Done 结束返回
const doClickTransferDoneAndGoBack = () => {
    // 点击 back
    console.log(Constant.UI_SDK_VERSION + "doClickTransferDoneAndGoBack-开始操作点击 Done");
    click(VodafoneGhsPageTag.sendMoneySuccessPageDoneTag1);
    sleep(500);
    click(VodafoneGhsPageTag.sendMoneySuccessPageDoneTag1);
    return true;
}

// 操作 点击 Done 结束返回
const doClickTransferFailAndGoBack = () => {
    // 点击 back
    console.log(Constant.UI_SDK_VERSION + "doClickTransferFailAndGoBack-开始操作点击 Done");
    click(VodafoneGhsPageTag.sendMoneySuccessPageFailTag1);
    sleep(500);
    click(VodafoneGhsPageTag.sendMoneySuccessPageFailTag1);
    return true;
}

// 操作 点击 Transactions
const doClickCheckBills = () => {
    // 点击 Transactions
    console.log(Constant.UI_SDK_VERSION + "doClickCheckBills-开始操作点击 Transactions");
    click(VodafoneGhsPageTag.homePageTag4);
    return true;
}

// 操作 点击 确认查看流水
const doClickBillCheckProceed = () => {
    // 点击 Transactions
    console.log(Constant.UI_SDK_VERSION + "doClickBillCheckProceed-开始操作点击 ok please proceed");
    click(VodafoneGhsPageTag.transactionAskPageTag4);
    sleep(1000);
    return true;
}

// 操作 输入pin码-查看流水
const doInputBillCheckPin = () => {
    // 点击 Transactions
    console.log(Constant.UI_SDK_VERSION + "doInputBillCheckPin-开始操作输入pin码");
    return doInputPinCode();
}


// ==================== 流水操作-start ====================
// 上报缓存记录
const mBillIdsCached = [];


/**
 *  深拷贝首页短流水记录
 */
const doDeepCloneShortBills = (arr1, arr2) => {
    if (!arr2) {
        return;
    }

    if (!arr1) {
        arr1 = [];
        return;
    }

    // 重置
    arr1.length = 0;
    // 深拷贝
    for (let di = 0; di < arr2.length; di++) {
        let diItem = arr2[di];
        let cloneItem = {};
        // rowData.amount = amountValue;
        // rowData.status = statusValue;
        // rowData.dateTime = curText;
        // rowData.txnId = transactionIDValue;
        // rowData.charge = chargeValue;

        cloneItem.amount = diItem.amount;
        cloneItem.dateTime = diItem.dateTime;
        cloneItem.status = diItem.status;
        cloneItem.txnId = diItem.txnId;
        cloneItem.charge = diItem.charge;

        arr1.push(cloneItem);
    }
};

// 新增流水详情缓存
const doAddBillRecord = (billItem) => {
    if (billItem) {
        let txnId = billItem.txnId;
        if (doIsBillRecordExist(transactionID)) {
            return false;
        } else {
            mBillIdsCached.push(billItem);
            return true;
        }
    }
    return false;
};

// 查询交易流水是否存在缓存
const doIsBillRecordExist = (transactionID) => {
    if (!transactionID) {
        return false;
    }

    for (let i = 0; i < mBillIdsCached.length; i++) {
        let item = mBillIdsCached[i];
        if (item.txnId.startsWith(transactionID)) {
            console.log(Constant.UI_SDK_VERSION + "doIsBillRecordExist-交易id已存在, 不作处理-" + transactionID);
            return true;
        }
    }
    console.log(Constant.UI_SDK_VERSION + "doIsBillRecordExist-交易id不存在, 增加到缓存-" + transactionID);

    return false;
};

// 查询当前屏的数据
const doGetBillsForCurrentScreen = (isFirstScreen) => {
    // 数据列表
    let dataList = [];
    // 是否到底部了
    let didBottom = false;

    // 判断是否有button
    let buttonList = className("Button").find();
    for (let index = 0; index < buttonList.length; index++) {
        let curTv = buttonList[index];
        let curText = curTv.text() || "";
        if (curText.indexOf(VodafoneGhsPageTag.transactionListBottomTagPrev) !== -1) {
            didBottom = true;
            break;
        }
        if (curText.indexOf(VodafoneGhsPageTag.transactionListBottomTagNext) !== -1) {
            didBottom = true;
            break;
        }
    }
    buttonList.length = 0;
    buttonList = null;

    // 读取当前列表
    let textList = className("TextView").find();
    let startIndex = 0;
    while (startIndex < textList.length) {
        let curTv = textList[startIndex];
        let curText = curTv.text() || "";

        // 判断是否到底
        if (curText.indexOf(VodafoneGhsPageTag.transactionListBottomTagPrev) !== -1) {
            didBottom = true;
        }
        if (curText.indexOf(VodafoneGhsPageTag.transactionListBottomTagNext) !== -1) {
            didBottom = true;
        }

        // 判断是否为有效的记录
        let isRecordTagDate = BaseStringUtil.isDigitAndLineStartOnly(curText);
        console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-当前: " + startIndex + ", 内容: " + curText + ", isRecordTagDate: " + isRecordTagDate + ", didBottom" + didBottom);

        if (isRecordTagDate) {
            // 这是行开头, 再判断是否为完整的行记录
            let amountIndex = (startIndex + 1);
            let amountTv = textList[amountIndex];
            let amountValue = amountTv.text() || "";
            let statusValue = null;
            let chargeValue = null;
            let transactionIDValue = null;
            let transactionIDValueIndex = -1;
            let transactionIDValueBottom = 0;

            // 找到 status
            for (let findIndex = startIndex; findIndex < textList.length; findIndex++) {
                let findTv = textList[findIndex];
                let findText = findTv.text() || "";
                if (findText.indexOf(VodafoneGhsPageTag.transactionListItemTagStatus) !== -1) {
                    let findValueIndex = (findIndex + 1);
                    if (findValueIndex < textList.length) {
                        let findValueTv = textList[findValueIndex];
                        statusValue = findValueTv.text() || "";
                    }
                    break;
                }
            }

            // 找到 charge
            for (let findIndex = startIndex; findIndex < textList.length; findIndex++) {
                let findTv = textList[findIndex];
                let findText = findTv.text() || "";
                if (findText.indexOf(VodafoneGhsPageTag.transactionListItemTagCharge) !== -1) {
                    let findValueIndex = (findIndex + 1);
                    if (findValueIndex < textList.length) {
                        let findValueTv = textList[findValueIndex];
                        chargeValue = findValueTv.text() || "";
                    }
                    break;
                }
            }

            // 找到 transaction id
            for (let findIndex = startIndex; findIndex < textList.length; findIndex++) {
                let findTv = textList[findIndex];
                let findText = findTv.text() || "";
                if (findText.indexOf(VodafoneGhsPageTag.transactionListItemTagTransactionID) !== -1) {
                    let findValueIndex = (findIndex + 1);
                    if (findValueIndex < textList.length) {
                        let findValueTv = textList[findValueIndex];

                        // 判断 transaction id 是否在可视范围内 -- vodafone 不用考虑翻屏
                        let canClick = true;// (findValueTv.bounds().bottom <= device.height);
                        console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-transaction id: " + findText + ", top: " + findValueTv.bounds().top + ", bottom: " + findValueTv.bounds().bottom + ", canClick: " + canClick);

                        if (!canClick) {
                            // 不是有效的行数据, 需要往下滑
                            console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-已经读完当前屏幕的有效数据, 跳出循环,  最后一行的Y坐标: " + findValueTv.bounds().bottom);
                            startIndex = textList.length;
                            continue;
                        }

                        // 设置值
                        transactionIDValueIndex = findValueIndex;
                        transactionIDValue = findValueTv.text() || "";
                        // 最后一行的Y坐标
                        transactionIDValueBottom = findValueTv.bounds().bottom;
                    }
                    break;
                }
            }

            // 如果全部都有效，才缓存
            if (amountValue && statusValue && chargeValue && transactionIDValue) {
                // 添加缓存
                let rowData = {};
                rowData.amount = amountValue;
                rowData.status = statusValue;
                rowData.dateTime = curText;
                rowData.txnId = transactionIDValue;
                rowData.charge = chargeValue;
                rowData.top = amountTv.bounds().top;
                rowData.bottom = transactionIDValueBottom;
                rowData.centerX = amountTv.bounds().centerX();
                rowData.centerY = amountTv.bounds().centerY();
                dataList.push(rowData);

                // let billItem = {
                //     dateTime: "",
                //     amount: "",
                //     name: "",
                //     txnId: "",
                //     type: "",
                //     txnFee: "",
                //     toAddr: Constant.getMtn(),
                //     fromAddr: "",
                //     phone: Constant.getMtn()
                // };

                // 添加缓存
                doAddBillRecord(rowData);

                console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-读完-准备下一个游标=====");
                // 更新起始位置
                startIndex = (transactionIDValueIndex + 1);
                // sleep(1 * 1000);
                continue;
            }
        }
        startIndex += 1;
    }

    textList.length = 0;
    textList = null;

    // 找出最后一个有效行的底部坐标
    let lastValidRowY = 0;
    if (dataList.length > 0) {
        let lastItem = dataList[dataList.length - 1];
        lastValidRowY = lastItem.bottom;
    }

    // 打印
    console.log(Constant.UI_SDK_VERSION + "doGetBillsForCurrentScreen-共有效数据: " + dataList.length);
    console.log(dataList);

    return { dataList: dataList, didBottom: didBottom, lastValidRowY: lastValidRowY };
};

// 处理每个版页的数据需求
const doScanBillsForEachScreen = () => {

    // 控制缓存不超过20条
    let needDelCount = (mBillIdsCached.length - 20);
    if (needDelCount > 0) {
        mBillIdsCached.splice(0, needDelCount);
    }

    // 最多遍历5次, 测试来看足够了
    let xPullStart = (device.width * 0.8);
    let yPullStart = 200;
    let yPullEnd = (device.height - 60);

    // 滑动到顶部
    swipe(xPullStart, yPullStart, xPullStart, yPullEnd, 1000);
    sleep(2 * 1000);

    for (let pageSize = 0; pageSize < 20; pageSize++) {
        console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-pageSize:" + pageSize + "==========");

        // 先查出当前屏的有效数据
        let curScreenBillInfo = doGetBillsForCurrentScreen(pageSize === 0);
        let curScreenBillList = curScreenBillInfo.dataList;
        let didBottom = curScreenBillInfo.didBottom;

        // 如果到底了，直接返回
        if (didBottom) {
            console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-所有流水数据抓取结束===");
            // 上传数据
            // ...
            console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-开始上报数据===");
            sleep(1000);
            back();
            sleep(1000);
            return true;
        }

        // 拿到最后一个记录，取bottom为滑动起点，往上滑一屏，yEnd = 200
        if (curScreenBillList.length > 0) {
            let item = curScreenBillList[curScreenBillList.length - 1];
            console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-yStart: " + item.bottom + ", yEnd: " + yPullStart);
            swipe(xPullStart, item.bottom, xPullStart, yPullStart, 2000);
            sleep(3000);
        }
    }

    // 如果没有数据，直接返回
    console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-流水流程结束===");
    sleep(1000);

    // 上报数据
    console.log(Constant.UI_SDK_VERSION + "doScanBillsForEachScreen-开始保存流程信息")
    let detailInfo = {
        mno: Constant.WALLET_VODAFONE_GHS_MNO,
        phone: Constant.getMtn(),
        bills: []
    }
    for (let i = 0; i < mBillIdsCached.length; i++) {
        let oriItem = mBillIdsCached[i];
        let billItem = {};
        billItem.mno = Constant.WALLET_VODAFONE_GHS_MNO;
        billItem.dateTime = oriItem.dateTime;
        billItem.amount = oriItem.amount;
        billItem.txnId = oriItem.txnId;
        billItem.charge = oriItem.charge;
        billItem.status = oriItem.status;
        billItem.phone = Constant.getMtn();
        detailInfo.bills.push(item);
    }
    let url = ApiUrl.saveBills();
    BaseHttpUtil.sendPostSync(url, detailInfo)

    detailInfo.bills.length = 0;
    detailInfo.bills = [];

    sleep(1000);

    back();
    sleep(1000);
    return true;
};

// ==================== 流水操作-end ====================


module.exports = {
    doLogin: doLogin,
    doPin: doPin,
    doGetHomeBalance: doGetHomeBalance,
    doClickHomeTab: doClickHomeTab,
    doClickSendMoney: doClickSendMoney,
    doClickVodafonePayment: doClickVodafonePayment,
    doInputTargetAccount: doInputTargetAccount,
    doConfirmSendMoney: doConfirmSendMoney,
    doInputSendMoneyPassword: doInputSendMoneyPassword,

    doClickTransferFailAndGoBack: doClickTransferFailAndGoBack,
    doClickTransferDoneAndGoBack: doClickTransferDoneAndGoBack,

    doClickBillCheckProceed: doClickBillCheckProceed,
    doInputBillCheckPin: doInputBillCheckPin,

    doClickCheckBills: doClickCheckBills,

    doGetBillsForCurrentScreen: doGetBillsForCurrentScreen,
    doScanBillsForEachScreen: doScanBillsForEachScreen
};